import { useCallback, useRef, useState } from "react";
import { TouchableOpacity, StyleSheet, Text, View, Image } from "react-native";
import { determineCurrentDevice, getStorageData, setStorageData } from "utils";
import { useFocusEffect } from "@react-navigation/native";
import Spinner from "react-native-loading-spinner-overlay";
import { manager } from "utils/bleManage";
import { useAppSelector, useAppDispatch } from "app/store";
import { setConnectedDevice, setSupconnectedDevice } from "app/modules/app";
import toast from "utils/toast";
import translate from "utils/translate";
const Buffer = require("@craftzdog/react-native-buffer").Buffer;
export default ({
  navigation,
  route: { params },
}: RootStackScreenProps<"connect">) => {
  const bindList = useRef<BindDevice[]>([]);
  const [loading, setLoading] = useState(false);
  const connectedDevice = useAppSelector((state) => {
    return state.app.connectedDevice;
  });
  const SupConnectedDevice = useAppSelector((state) => {
    return state.app.SupConnectedDevice;
  });
  const dispatch = useAppDispatch();
  const unbind = () => {
    bindList.current.splice(params.index, 1);
    setStorageData("bleList", JSON.stringify(bindList.current)).then(
      async () => {
        if (connectedDevice) {
          await onDisConnect();
          dispatch(setConnectedDevice(null));
        }
        navigation.goBack();
        toast(translate("main.success"));
      }
    );
  };
  const onConnect = () => {
    manager.state().then((value) => {
      if (value !== "PoweredOn") return toast(translate("home.bind.enabled"));
      setLoading(true);
      manager
        .connectToDevice(params.uuid)
        .then(async () => {
          dispatch(setConnectedDevice(params.uuid));
          manager
            .discoverAllServicesAndCharacteristicsForDevice(params.uuid)
            .then((device) => {
              device
                .services()
                .then(async (services) => {
                  const item = determineCurrentDevice(services);
                  if (item) {
                    const characteristicsList = await item.characteristics();
                    for (let current of characteristicsList) {
                      if (
                        current.isWritableWithResponse &&
                        current.isNotifiable
                      ) {
                        current
                          .writeWithoutResponse(
                            Buffer.from("A3", "hex").toString("base64")
                          )
                          .then(() => {
                            setLoading(false);
                            device.onDisconnected((err) => {
                              if (err) {
                                toast(translate("home.bind.terminal"));
                              }
                              dispatch(setConnectedDevice(null));
                              SupConnectedDevice?.remove();
                              dispatch(setSupconnectedDevice(null));
                            });
                          });

                        // const Subscription = current.monitor(
                        //   (err, characteristic) => {
                        //     if (err && err.reason) {
                        //       toast(err.reason);
                        //       setLoading(false);
                        //       return Subscription.remove();
                        //     }
                        //     if (characteristic?.value) {
                        //       setLoading(false);
                        //       toast("连接成功");
                        //     }
                        //     return Subscription.remove();
                        //   }
                        // );
                        // return current.writeWithResponse(
                        //   Buffer.from("A3", "hex").toString("base64")
                        // );
                      }
                    }
                  }
                })
                .catch(() => {
                  setLoading(false);
                  toast(translate("main.error"));
                });
            });
        })
        .catch(() => {
          setLoading(false);
          toast(translate("main.error"));
        });
    });
  };
  const onDisConnect = async () => {
    const device = await manager.cancelDeviceConnection(params.uuid);
    dispatch(setConnectedDevice(null));
    SupConnectedDevice?.remove();
    return device;
  };
  useFocusEffect(
    useCallback(() => {
      getStorageData("bleList").then((value) => {
        bindList.current = value ? JSON.parse(value) : [];
      });
    }, [])
  );
  return (
    <View style={{ flex: 1, backgroundColor: "#fff" }}>
      <Spinner
        visible={loading}
        textContent={translate("main.loading") + "..."}
        textStyle={{
          color: "rgba(10, 89, 247, .8)",
        }}
        color="rgba(10, 89, 247, .8)"
        cancelable
      />
      <View
        style={{
          flexDirection: "row",
          alignItems: "center",
          justifyContent: "space-around",
          marginTop: 20,
          marginBottom: 20,
          borderBottomWidth: 1,
          paddingBottom: 20,
          borderBottomColor: "rgba(0,0,0,0.08)",
        }}
      >
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
          }}
        >
          <Image
            style={styles.image}
            source={require("assets/images/ble.png")}
          ></Image>
          <Text>{params?.name ?? translate('main.WeighingApparatus')}</Text>
        </View>
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
          }}
        >
          <Image
            style={styles.image}
            source={require("assets/images/status.png")}
          ></Image>
          <Text
            style={{
              color: connectedDevice ? "#0A59F7" : undefined,
            }}
          >
            {connectedDevice
              ? translate("home.bind.Connected")
              : translate("home.bind.unconnected")}
          </Text>
        </View>
      </View>
      <View style={{ marginBottom: 20 }}>
        <Text
          style={{
            textAlign: "center",
            marginBottom: 20,
            color: connectedDevice ? "#ff0000" : undefined,
            fontWeight: connectedDevice ? "bold" : undefined,
          }}
        >
          {connectedDevice
            ? translate("home.bind.tip3")
            : translate("home.bind.tip4")}
        </Text>
        <Text
          style={{
            textAlign: "center",
            color: "rgba(0, 0, 0, 0.60)",
          }}
        >
          {translate("home.bind.tip2")}
        </Text>
        <Text
          style={{
            textAlign: "center",
            color: "rgba(0, 0, 0, 0.60)",
          }}
        >
          {translate("home.bind.tip1")}
        </Text>
      </View>
      {!connectedDevice ? (
        <TouchableOpacity style={styles.button} onPress={onConnect}>
          <Text
            style={{
              textAlign: "center",
              color: "#fff",
            }}
          >
            {translate("home.bind.Connecting")}
          </Text>
        </TouchableOpacity>
      ) : (
        <TouchableOpacity style={styles.button} onPress={onDisConnect}>
          <Text
            style={{
              textAlign: "center",
              color: "#fff",
            }}
          >
            {translate("home.bind.disconnect")}
          </Text>
        </TouchableOpacity>
      )}
      <TouchableOpacity
        style={{ ...styles.button, backgroundColor: "#ff0000" }}
        onPress={() => {
          unbind();
        }}
      >
        <Text
          style={{
            textAlign: "center",
            color: "#fff",
          }}
        >
          {translate("home.bind.unbind")}
        </Text>
      </TouchableOpacity>
    </View>
  );
};
const styles = StyleSheet.create({
  button: {
    backgroundColor: "#0A59F7",
    width: "80%",
    height: 50,
    marginBottom: 20,
    borderRadius: 16,
    alignItems: "center",
    justifyContent: "center",
    alignSelf: "center",
  },
  image: {
    width: 60,
    height: 67,
  },
});
